# 学习课程：中文文本挖掘
# 学习学生：姜浩然

import pandas as pd
import re
raw = pd.read_csv(r"D:\python\金庸-射雕英雄传txt精校版.txt",
                  names = ['txt'], sep ='aaa', encoding ="GBK" ,engine='python')
def m_head(tmpstr):
    return tmpstr[:1]

def m_mid(tmpstr):
    return tmpstr.find("回 ")

raw['head'] = raw.txt.apply(m_head)
raw['mid'] = raw.txt.apply(m_mid)
raw['len'] = raw.txt.apply(len)
# 章节判断
chapnum = 0
for i in range(len(raw)):
    if raw['head'][i] == "第" and raw['mid'][i] > 0 and raw['len'][i] < 30:
        chapnum += 1
    if chapnum >= 40 and raw['txt'][i] == "附录一：成吉思汗家族":
        chapnum = 0
    raw.loc[i, 'chap'] = chapnum

# 删除临时变量
del raw['head']
del raw['mid']
del raw['len']

# 获取某一章节内容
def inputchapter(number):
    tmpchap = raw[raw['chap'] == number].copy()
    tmpchap.reset_index(drop=True, inplace=True)
    tmpchap['paraidx'] = tmpchap.index
    return tmpchap

# 将长句子进行细分
def cutchapter(number):
    temp = inputchapter(number)
    list1 = [temp['txt'][0]]
    list2 = [temp['paraidx'][0]]
    for i in range(1,len(temp)):
        tmpstr = temp['txt'][i]
        sentences = re.findall('(.*?[？。！；：](’|”)?)', tmpstr)
        for j in sentences:
            list1.append(j[0])
            list2.append(i)
        newtmpchap = pd.DataFrame({'txt':list1,'paraidx':list2})
    return newtmpchap
if __name__ == '__main__':
    result = []
    temp = cutchapter(int(input('请输入您想看的章节:')))    # 输入章节名
    print(temp)
    for i in temp['txt']:
        result.append(i)
    print(result)






